package com.bjpowernode.mvc.controller;

import cn.hutool.core.util.PhoneUtil;
import com.bjpowernode.common.constant.AppConstants;
import com.bjpowernode.common.enums.RespCode;
import com.bjpowernode.db.domain.SysUser;
import com.bjpowernode.mvc.model.result.CommonResult;
import com.bjpowernode.mvc.service.inter.SmsService;
import com.bjpowernode.mvc.service.inter.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
@RestController
@RequestMapping("/sms")
public class SmsController {

    private final UserService userService;

    private final SmsService smsService;

    //接收 注册验证码
    @GetMapping("/code/register")
    public CommonResult smsRegister(@RequestParam String phone) {
        //利用hutool工具库的PhoneUtil类检查手机号格式是否正确(正则表达式)
        if (PhoneUtil.isPhone(phone)) {
            //1、查询手机号是否注册过
            SysUser sysUser = userService.queryByPhone(phone);
            if (sysUser != null) {
                //已经注册过，提示请登录
                return CommonResult.warn(RespCode.PHONE_USER_EXITS);
            }

            //2、发送短信验证码
            String result = smsService.sendSms(AppConstants.ACTION_REGISTER, phone);
            if (result.equals(RespCode.OK.name())) {
                return CommonResult.ok();
            }
        }
        return CommonResult.warn();
    }


    //接收登录验证码

    @GetMapping("/code/login")
    public CommonResult smsLogin(@RequestParam String phone) {
        //利用hutool工具库检查手机号格式是否正确(正则表达式)
        if (PhoneUtil.isPhone(phone)) {
            //1、查询手机号是否注册过
            SysUser sysUser = userService.queryByPhone(phone);
            if (sysUser == null) {
                //没有注册过，提示去注册
                return CommonResult.warn(RespCode.PHONE_USER_NOT_EXITS);
            }

            //2、进行登录
            String result = smsService.sendSms(AppConstants.ACTION_LOGIN, phone);
            if (result.equals(RespCode.OK.name())) {
                return CommonResult.ok();
            }
        }
        return CommonResult.warn();
    }
}
